package com.totoro.tyrank.executor.action.impl;

import com.totoro.tyrank.TyRank;
import com.totoro.tyrank.constants.ActionConst;
import com.totoro.tyrank.constants.StaticSystemVarConst;
import com.totoro.tyrank.executor.action.ActionExecutor;
import com.totoro.tyrank.utils.ColorUtil;
import com.totoro.tyrank.utils.PapiUtil;
import com.totoro.tyrank.utils.StrUtil;
import org.bukkit.entity.Player;

public class TitleActionExecutor implements ActionExecutor {
    @Override
    public void execute(String actionText, Player player) {
        actionText = StrUtil.getContentAfter(actionText, ActionConst.TITLE);
        actionText = PapiUtil.parseStrPapiVariable(player, actionText);
        // 先通过 # 分割标题内容和标题时间
        String[] titleTypeSplit = actionText.split("#");
        if(titleTypeSplit.length != 2) {
            // 如果不等于2，就是没有填写标题时间或写错格式
            TyRank.getInstance().getServer().getConsoleSender().sendMessage
                    (StaticSystemVarConst.CONSOLE_PREFIX + TyRank.getLanguageManager().getLanguageData().getMsg().getTitleActionError().replaceAll("<player>", player.getName()));
            return;
        }
        String titleTexts = titleTypeSplit[0];
        String titleDates = titleTypeSplit[1];
        // 标题内容获取
        // 通过<subTitle> 分割主标题与副标题
        String[] titleTextSplit = titleTexts.split("<subTitle>");
        // 主标题与副标题
        String mainTitle = titleTextSplit[0];
        String subTitle = "";
        if(titleTextSplit.length >= 2) {
            subTitle = titleTextSplit[1];
        }

        // 标题时间获取
        String[] titleDateSplit = titleDates.split("@");
        int fadeIn = 10;
        int stay = 70;
        int fadeOut = 20;
        try {
            if (titleDateSplit.length >= 1) {
                fadeIn = Integer.parseInt(titleDateSplit[0]);
            }
            if (titleDateSplit.length >= 2) {
                stay = Integer.parseInt(titleDateSplit[1]);
            }
            if (titleDateSplit.length >= 3) {
                fadeOut = Integer.parseInt(titleDateSplit[2]);
            }
        } catch (NumberFormatException e) {
            TyRank.getInstance().getServer().getConsoleSender().sendMessage
                    (StaticSystemVarConst.CONSOLE_PREFIX + TyRank.getLanguageManager().getLanguageData().getMsg().getTitleActionError().replaceAll("<player>", player.getName()));
            e.printStackTrace();
        }
        player.sendTitle(mainTitle, subTitle, fadeIn, stay, fadeOut);
    }
}
